package com.rjwh.dingdong.client.adapter;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.net.Uri;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.util.FileUtils;
import com.rjwh.dingdong.client.util.GlideDownloadImageUtil;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.widget.PhotoView;
import com.rjwh.dingdong.client.widget.photoview.PhotoViewAttacher.OnPhotoTapListener;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 照片浏览列表
 *
 * @author 王小珂
 * @ClassName ImageShowPagerAdapter
 * @Description TODO(这里用一句话描述这个类的作用)
 * @date 2015-10-19 下午4:49:59
 * @history 1.YYYY-MM-DD
 * author:
 * description:
 */
public class ImageShowPagerAdapter extends PagerAdapter {

    private List<String> images;
    private List<String> localList;
    private LayoutInflater inflater;
    private Activity activity;

    public ImageShowPagerAdapter(List<String> images, List<String> localList, Activity activity) {
        this.images = images;
        this.localList = localList;
        inflater = LayoutInflater.from(activity);
        this.activity = activity;
    }

    @Override
    public int getCount() {
        if (localList != null && !localList.isEmpty()) {
            return localList.size();
        } else {
            return images == null || images.isEmpty() ? 0 : images.size();
        }
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        View convertView = inflater.inflate(R.layout.image_list, null);
        PhotoView photoView = (PhotoView) convertView.findViewById(R.id.photoalbum_listimage_icon);
        final ProgressBar spinner = (ProgressBar) convertView.findViewById(R.id.image_parogressbar);
        if (images != null && !images.isEmpty()) {
            String pathStr = images.get(position);
            final String path = pathStr.replace("/tp/", "/mp/");
            LogUtil.d("ImageShowPagerAdapter", "path: " + path);
            Glide.with(activity).load(path).placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_pic_holder).dontAnimate().thumbnail(0.1f).diskCacheStrategy(DiskCacheStrategy.ALL).into(photoView);

            photoView.setOnPhotoTapListener(new OnPhotoTapListener() {

                @Override
                public void onPhotoTap(View view, float x, float y) {
                    // TODO Auto-generated method stub
                    activity.finish();
                }
            });
            photoView.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    showBottomDialog(path);
                    return true;
                }
            });
        } else {
            String picPath = localList.get(position);
            if (!AsStrUtils.isEmpty(picPath)) {
                Glide.with(activity).load("file://" + picPath).placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_pic_holder).dontAnimate().diskCacheStrategy(DiskCacheStrategy.ALL).into(photoView);
            }
        }
        container.addView(convertView);
        return convertView;
    }

    protected void showBottomDialog(final String path) {
        new android.support.v7.app.AlertDialog.Builder(activity)
                .setMessage("是否保存到本地?")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.cancel();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        saveImageToGallery(path);
                        dialog.dismiss();
                    }
                })
                .show();
    }


    private void saveImageToGallery(final String path) {

        Observable.just("")
                .compose(RxPermissions.getInstance(activity).ensure(Manifest.permission.WRITE_EXTERNAL_STORAGE))
                .observeOn(Schedulers.io())
                .filter(new Func1<Boolean, Boolean>() {

                    @Override
                    public Boolean call(Boolean aBoolean) {

                        return aBoolean;
                    }
                })
                .flatMap(new Func1<Boolean, Observable<Uri>>() {

                    @Override
                    public Observable<Uri> call(Boolean aBoolean) {

                        return GlideDownloadImageUtil.saveImageToLocal(activity, path);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Uri>() {

                    @Override
                    public void call(Uri uri) {

                        File appDir = new File(FileUtils.getPicStorageDirectory());
                        String msg = String.format("图片已保存至 %s 文件夹", appDir.getAbsolutePath());
                        Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
                    }
                }, new Action1<Throwable>() {

                    @Override
                    public void call(Throwable throwable) {

                        Toast.makeText(activity, "保存失败,请重试", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        container.removeView((View) object);
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }
}
